package com.sticktogether.photoreceiver;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.MediaStore;

import com.sticktogether.server.ServerCommunication;

public class PictureReceiver extends BroadcastReceiver {

	@SuppressLint("SimpleDateFormat")
	@Override
	public void onReceive(Context context, Intent intent) {
    	
    		
		// get a string with the path of the image
		String filePath = getRealPathFromURI(intent.getData(), context);
		
		// get the current date to know when the photo has been taken
		String timeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		
		// save the path and date in the database
		PhotoDatabase photos = ServerCommunication.getPhotoDb(context);
		synchronized (photos) {
			SQLiteDatabase db = photos.getWritableDatabase();
		    ContentValues values = new ContentValues();
		    values.put("album_id", 0);
		    values.put("path", filePath);
		    values.put("time", timeString);
			db.insert("photos", null, values);
			db.close();
		}
		
		// initiate upload if WIFI is enabled, or if upload only in WIFI is disabled
    	SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
		if(!sharedPref.getBoolean("upload_in_wifi_only", true) || WifiChangeBroadcastReceiver.checkWifiConnected(context)) {
			ServerCommunication.getAlbumId(timeString, context);
		}
			
	}

	public String getRealPathFromURI(Uri contentUri, Context context) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			String url = cursor.getString(column_index);
			cursor.close();
			return url;
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

}
